package net.sf.midollo.net.httptunnel.server.servlet;

import net.sf.midollo.net.httptunnel.HttpTunnelConstants;
import net.sf.midollo.net.httptunnel.server.HttpTunnelServer;
import net.sf.midollo.net.httptunnel.server.HttpTunnelServerSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class HttpTunnelServletHelper implements HttpTunnelConstants {

	protected final HttpTunnelServer server;

	public HttpTunnelServletHelper(HttpTunnelServer server) {
		this.server = server;
	}

	public void dispatch(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
		String sessionId = httpServletRequest.getHeader(SESSION_HEADER_NAME);
		HttpTunnelServerSession session;
		if (sessionId == null) {
			session = this.server.createSession();
			httpServletResponse.setContentType("text/plain");
			httpServletResponse.setHeader(SESSION_HEADER_NAME, session.getSessionId());
			httpServletResponse.flushBuffer();
			OutputStream os = httpServletResponse.getOutputStream();
			session.writeLoop(os);
		} else {
			int contentLength = httpServletRequest.getContentLength();
			if (contentLength < 0)
				throw new ServletException("Content-Length required");
			session = this.server.getSession(sessionId);
			InputStream is = httpServletRequest.getInputStream();
			session.readLoop(is, contentLength);
			httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
			httpServletResponse.flushBuffer();
		}
	}
}
